package com.omnisyr.textrebuilder.common;

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;

import javax.imageio.ImageIO;

import com.omnisyr.textrebuilder.util.structure.SimpleArrayList;

public class Palette {

	private SimpleArrayList<Color> colors = new SimpleArrayList<Color>();

	public Palette(Color... colors) {

		for (Color color : colors) {

			this.colors.add(color);

		}

	}

	public Palette append(Color color) {

		this.colors.add(color);

		return this;

	}

	public void saveAs(File file) {

		String name = file.getName();

		if (name.endsWith("png")) {

			this.saveAsPNG(file);

			return;

		}

		if (name.endsWith("csv")) {

			this.saveAsCSV(file);

			return;

		}

	}

	private void saveAsPNG(File file) {

		try {

			int loop = 0;
			BufferedImage image = new BufferedImage(16, this.colors.size() * 16, 1);

			for (Color color : this.colors) {

				for (int i = 0; i < 16; i++) {

					for (int j = 0; j < 16; j++) {

						image.setRGB(i, 16 * loop + j, color.toInteger());

					}

				}

				loop++;

			}

			ImageIO.write(image, "png", file);

		} catch (Exception ex) {

		}

	}

	private void saveAsCSV(File file) {

		try {

			if (file.exists()) {

				file.delete();

			}

			file.createNewFile();

			PrintWriter mainTextWriter = new PrintWriter(new BufferedWriter(new FileWriter(file)));

			for (Color color : this.colors) {

				String line = color.toSingle(0) + "," + color.toSingle(1) + "," + color.toSingle(2);

				mainTextWriter.println(line);

			}

			mainTextWriter.close();

		} catch (Exception ex) {

		}

	}

	public Palette[] split() {

		Palette[] rgb = new Palette[3];

		for (Color color : this.colors) {

			for (int i = 0; i < 3; i++) {

				rgb[i].append(new Color(color.toSingle(i)));

			}

		}

		return rgb;

	}

}
